<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customer_friend_model extends CI_Model
{
	public function set_friend_req_as_handled($reqUid)
	{
		$requestInfo = array(
				"handled"=>TRUE,
		);
	
	
	
		$this->db->where(array("uid"=>get_uid(), "reqUid"=>$reqUid));
		$this->db->update("userfriendrequest",$requestInfo);
	}
	
	public function push_shared_info_to_friend($uid, $friend_uid)
	{
		$this->load->model("customer_health_model", "health_model");
		$this->load->model("personal_health_info_model", "health_info_model");
		
		$all_shared_health_info = $this->health_model->get_all_shared_health_info($uid);
		
		while($shared_health_info = current($all_shared_health_info))
		{
			$health_info_id = $shared_health_info["health_info_id"];
			$field = $shared_health_info["field"];
			$this->health_model->push_health_info_to_friend($uid, $friend_uid, $field, $health_info_id);
			next($all_shared_health_info);
		}
		
		$all_shared_symptom = $this->health_info_model->get_all_shared_symptoms($uid);
		while($shared_symptom = current($all_shared_symptom))
		{
			$symptom_info_id = $shared_symptom->symptomInfoId;
			$this->health_info_model->push_symptom_to_friend($uid, $friend_uid, $symptom_info_id);
			next($all_shared_symptom);		
		}
	}
	
	public function get_user_friends($uid)
	{
		$this->db->where("uid", $uid);
		$query = $this->db->get("userfriends");
		
		if(!$query->num_rows())
			return null;
		
		$all_friends = array();
		
		$result = $query->result();
		foreach($result as $friendInfo)
		{
			$friend_uid = $friendInfo->friendUid;
			$all_friends[] = $friend_uid;
		}
		
		return $all_friends;
	}
	
	public function accept_friend_req($req_uid)
	{
		if(is_friend(get_uid(), $req_uid))
			return;
		
		$friendInfo1 = array(
				"uid"=>get_uid(),
				"friendUid"=>$req_uid,
		);
	
		$friendInfo2 = array(
				"uid"=>$req_uid,
				"friendUid"=>get_uid(),
		);
	
		$this->db->insert("userfriends", $friendInfo1);
		$this->db->insert("userfriends", $friendInfo2);
	
		$this->set_friend_req_as_handled($req_uid);
		
		$this->push_shared_info_to_friend(get_uid(), $req_uid);
		$this->push_shared_info_to_friend($req_uid, get_uid());
	}
	
	public function add_req_to_db($myUid, $friendUid)
	{
		//先检查用户是否发过请求，如果发过不重复处理
		$query = $this->db->get_where("userfriendrequest", array(
				"reqUid"=>$myUid,
				"uid"=>$friendUid,
				"handled"=>false,
		));
		if($query->num_rows()){
			//Some log can be added here!
			return;
		}
	
		$data = array(
				"reqUid"=>$myUid,
				"uid"=>$friendUid,
				"date"=>mysql_datetime()
		);
	
		$this->db->insert("userfriendrequest", $data);
	}
	
	public function get_all_req()
	{
		$uid = get_uid();
		$query = $this->db->get_where("userfriendrequest",array("uid"=>$uid, "handled"=>FALSE));
		return $query->result();
	}
	
	public function deny_friend_req($req_uid)
	{
		$this->set_friend_req_as_handled($req_uid);
	}
}
?>